<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">超级管理员登录</h2>

      <div class="form-item">
        <label>账号</label>
        <input type="text" v-model="loginData.account" placeholder="请输入账号">
      </div>

      <div class="form-item">
        <label>密码</label>
        <input type="password" v-model="loginData.password" placeholder="请输入密码">
      </div>

      <button class="login-btn" @click="login">登录</button>
    </div>

    <div class="system-title">
      <h1>靖边县人民政协</h1>
      <h2>智慧政务管理服务系统</h2>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
//调用后台接口完成注册
import { adminLoginService, getAdminInfoService } from '@/api/admin.js'
import { useTokenStore } from '@/stores/token.js'
import { useRouter } from 'vue-router'
import { useAdminStore } from '@/stores/admin.js'

const router = useRouter()
const tokenStore = useTokenStore();
const adminStore = useAdminStore()

//定义数据模型
const loginData = ref({
  account: '',
  password: '',
})


//定义表单校验规则
const rules = {
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ]
}

//登录函数
const login = async () => {
  try {
    // 表单验证 - 匹配后端的正则要求
    if (loginData.value.account === '' || loginData.value.password === '') {
      ElMessage.warning('账号或密码不能为空')
      return
    }
    if (!/^\S{5,16}$/.test(loginData.value.account)) {
      ElMessage.warning('账号必须是5-16位非空字符')
      return
    }
    if (!/^\S{5,16}$/.test(loginData.value.password)) {
      ElMessage.warning('密码必须是5-16位非空字符')
      return
    }

    //调用接口,完成登录
    let result = await adminLoginService({
      ...loginData.value
    });
    //把得到的token存储到pinia中
    tokenStore.setToken(result.data.token)
    //获取管理员详细信息
    const adminInfoResult = await getAdminInfoService()
    console.log("登录拉~管理员详细信息：", adminInfoResult)
    if (adminInfoResult.code === 200) {
      //存储完整的管理员信息
      adminStore.setAdminInfo(adminInfoResult.data)
    }
    //进行判断 弹出提示
    if (result.data.role === 1) {
      ElMessage.success(result.msg || '登录成功')
      //跳转到首页面
      router.push('/main').then(() => {
        window.location.reload()
      })
    } else {
      ElMessage.error('登录失败，您不是超级管理员！')
    }

  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.msg || '登录失败，请检查账号密码')
  }
}


onMounted(() => {
});

</script>

<style>
@import '@/assets/css/login.css';
</style>